package com.murray.assignment.controller;

import com.murray.assignment.pojo.Users;
import com.murray.assignment.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;

/**
 * @author Murray
 * @Date 2021/6/7
 * @Time 0:38
 */
@Controller
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UsersService usersService;

    /**
     * 处理用户进入登录注册页面
     *
     * @return
     */
    @RequestMapping("/register")
    public String register() {
        return "register";
    }

    /**
     * 处理使用用户名注册请求
     *
     * @return
     */
    @RequestMapping("/registByUsername")
    public String registByUsername(Users users) {
        Integer regist = usersService.registByUsername(users);
        if (regist > 0)
            return "login";
        else
            return "error";
    }

    /**
     * 处理使用手机号注册请求
     *
     * @param users
     * @return
     */
    @RequestMapping("/registByPhone")
    public String registByMobile(Users users) {
        Integer regist = usersService.registByMobile(users);
        if (regist > 0)
            return "login";
        else
            return "error";
    }

    /**
     * 处理异步请求，
     * 当控件失去焦点根据用户名或者手机号，判断用户是否已经存在
     *
     * @param users
     * @return
     */
    @RequestMapping(value = "/ajax", method = RequestMethod.GET)
    @ResponseBody
    public String ajax(Users users) {
        Integer existsUname = usersService.isExistsUname(users);
        return existsUname.toString();
    }

    /**
     * 处理登录请求
     *
     * @return 返回到登录页面
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        return "login";
    }

    /**
     * 处理登录请求，判断用户名及其密码是否正确
     *
     * @return 如果用户名和密码输入正确，则登录成功,否则失败，重新进入登录页面
     */
    @RequestMapping(method = RequestMethod.POST, value = "/login")
    @ResponseBody
    public String login(Users users, HttpSession session) {
        Users user = usersService.findUserByUnameAndUpwd(users);
        System.out.println(user);
        if (user == null) {
            return "failed";
        } else {
            session.setAttribute("user", user);
            return "success";
        }
    }

    @RequestMapping(value = "/loginSuccess", method = RequestMethod.GET)
    public String loginSuccess() {
        return "redirect:/index";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "login";
    }


}
